package com.mycat.alipay.server;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.google.gson.Gson;
import com.mycat.alipay.bizcontent.RefundContent;
import com.mycat.alipay.bizcontent.RefundQueryContent;
import com.mycat.alipay.config.AlipayConfig;
import com.mycat.exception.PaymentException;

/**
 * @desc 支付宝退款相关服务
 * @author roger
 * @date 2016年9月26日
 */
public class AliRefundServer {

	/**
	 * 支付宝申请退款
	 * 
	 * @param content
	 *            退款业务参数
	 * @return AlipayTradeRefundResponse
	 * @throws Exception
	 */
	public static AlipayTradeRefundResponse refund(RefundContent content) throws Exception {
		try {
			AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
					AlipayConfig.appId, AlipayConfig.private_key, "JSON", "utf-8", AlipayConfig.alipay_public_key);
			AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
			Gson gson = new Gson();

			request.setBizContent(gson.toJson(content));

			return alipayClient.execute(request);
		} catch (AlipayApiException e) {
			e.printStackTrace();
			throw new PaymentException("支付宝申请退款出现异常");
		}
	}

	/**
	 * 支付宝交易退款查询
	 * 
	 * @param content
	 *            退款查询业务参数
	 * @return AlipayTradeFastpayRefundQueryResponse
	 * @throws Exception
	 */
	public static AlipayTradeFastpayRefundQueryResponse refundQuery(RefundQueryContent content) throws Exception {
		try {
			AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
					AlipayConfig.appId, AlipayConfig.private_key, "JSON", "utf-8", AlipayConfig.alipay_public_key);
			AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
			Gson gson = new Gson();
			request.setBizContent(gson.toJson(content));

			AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(request);
			return response;
		} catch (AlipayApiException e) {
			e.printStackTrace();
			throw new PaymentException("支付宝查询交易退款出现异常");
		}
	}

}
